// ==UserScript==
// @name         ReaderIDCard
// @namespace    https://gitcode.com/yuzus/script
// @version      0.6
// @description  自动填充身份证号输入框(新中新)
// @match        *://*/ptyFee/*
// @grant        GM_xmlhttpRequest
// @run-at       document-end
// @downloadURL https://gitcode.com/yuzus/script/raw/main/ReaderIDCard.user.js
// @updateURL https://gitcode.com/yuzus/script/raw/main/ReaderIDCard.user.js
// ==/UserScript==

(function () {
    'use strict';
    function init() {
        if (!document.querySelector("#certNumber")) {
            setTimeout(init, 5000); // 轮询直到元素加载
            return;
        }

        document.querySelector("#certNumber").addEventListener('dblclick', async function () {
            const waitTime = 3;
            const t = Date.now();
            const url = `http://127.0.0.1:8989/api/ReadMsg?waitTime=${waitTime}&t=${t}`;
            GM_xmlhttpRequest({
                method: 'GET',
                url: url,
                onload: (response) => {
                    try {
                        const data = JSON.parse(response.responseText);
                        if (data.cardno) {
                            const event = new Event('input', { bubbles: true });
                            input.value = data.cardno;
                            input.dispatchEvent(event);
                            console.log('身份证号自动填充成功');
                        } else {
                            console.log('服务器返回数据格式错误');
                        }
                    } catch (e) {
                        console.error('JSON解析失败:', e);
                    }
                },
                onerror: (error) => {
                    console.error('请求失败:', error);
                },
                timeout: 5000 // 5秒超时
            });
        });
    }
    // 兼容不同加载状态的初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();